package com.zhanggm.ry.cart;

import com.google.common.collect.Maps;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.zhanggm.ry.cart.feign.ProductFeignClient;
import com.zhanggm.ry.cart.model.Sku;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 购物车
 */

@RestController
@RequestMapping("/cart/")
public class CartController extends BaseController {

    /**
     * 购物车Reids Key前缀
     */
    private String cartKey = "cart:";

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ProductFeignClient productFeignClient;


    /**
     * 添加购物车
     * @param skuId
     * @param num
     * @return
     */
    @GetMapping("add")
    public AjaxResult add(Long skuId,Integer num) {
        String userId = JwtUtils.getUserId(request.getHeader("token"));
        redisTemplate.opsForHash().put(cartKey + userId, skuId, num);
        return success();
    }

    /**
     * 我的购物车
     * @return
     */
    public AjaxResult my() {
        // 当前登录用户
        String userId = JwtUtils.getUserId(request.getHeader("token"));
        // 从Redis查询购物车数据
        Map<Long, Integer> cartMap = redisTemplate.opsForHash().entries(cartKey + userId);
        Set<Long> skuIdSet = cartMap.keySet();
        //批量查询商品信息
        List<Sku> skuIdList = productFeignClient.getSkuByIds(skuIdSet);
        // 循环设置商品数量和价格小计
        List<Sku> cartSkuList = skuIdList.stream().map(item -> {
            item.setNum(cartMap.get(item.getId()));
            item.setPrice(item.getPrice().multiply(new BigDecimal(item.getNum() + "")));
            return item;
        }).collect(Collectors.toList());
        //计算总计
        double total = skuIdList.stream().mapToDouble(item -> item.getTotal().doubleValue()).sum();
        //封装返回结构，商品列表和价格总计
        Map<String,Object> resultMap = Maps.newHashMap();
        resultMap.put("skuList", cartSkuList);
        resultMap.put("total", total);

        return success(resultMap);

    }

}
